package com.geely.design.pattern.behavioral.interpreter;

import java.util.Stack;

public class MyExpressionParser {

    private Stack<Interpreter> stack = new Stack<>();

    public int parse(String inputStr) {
        String[] itemArray = inputStr.split(" ");
        for (String symbol : itemArray) {
            if (!OperateUtil.isOperator(symbol)) {
                NumberInterpreter number = new NumberInterpreter(symbol);
                stack.push(number);
                System.out.println(String.format("入栈: %d", number.interpret()));
            } else {
                //运算符
                Interpreter firstExpression = stack.pop();
                Interpreter secondExpression = stack.pop();
                System.out.println(String.format("出栈: %d和%d",firstExpression.interpret(),secondExpression.interpret()));
                System.out.println("应用运算符: " + symbol);
                Interpreter resultInterpreter = OperateUtil.operate(firstExpression,secondExpression,symbol);
                int result = resultInterpreter.interpret();
                NumberInterpreter resultExpression = new NumberInterpreter(result);
                stack.push(resultExpression);
                System.out.println(String.format("阶段入栈: %d", resultExpression.interpret()));
            }

        }
        int result = stack.pop().interpret();
        return result;
    }

}
